<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { buyerGoodsPage } from "~/api/goods";

interface Props {
  defaultType: {
    id: string;
    name: string;
    [key: string]: any;
  };
}

const props = withDefaults(defineProps<Props>(), {
  defaultType: () => ({} as any),
});

const router = useRouter();

onMounted(() => {
  getList();
});

const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  firstTypeId: props.defaultType.id,
});

const list = ref<any[]>([]);
const pages = ref(0);
const recommendingListRef = ref<HTMLElement | null>(null);
const currentPage = ref(0); // 当前显示的页面索引

// 每页显示的项目数量
const itemsPerPage = 4;
// 容器总宽度
const containerWidth = 1200;
// 项目间距
const itemGap = 16;
// 计算每个项目的实际宽度：(总宽度 - (项目数-1) * 间距) / 项目数
// (1200 - 3 * 16) / 4 = (1200 - 48) / 4 = 1152 / 4 = 288px
const itemWidth = Math.floor((containerWidth - (itemsPerPage - 1) * itemGap) / itemsPerPage);
// 每页的总宽度（用于滚动计算）
const pageWidth = containerWidth;

const getList = async () => {
  try {
    const data = await buyerGoodsPage(queryParams.value);
    console.log('商品数据详情:', {
      total: data.total,
      rowsLength: data.rows?.length,
      rows: data.rows,
      queryParams: queryParams.value
    });
    
    list.value = data.rows || [];
    // 计算总页数：总记录数 / 每页大小，向上取整
    pages.value = Math.ceil((data.total || 0) / queryParams.value.pageSize);
    
    console.log('处理后的数据:', {
      listLength: list.value.length,
      pages: pages.value,
      total: data.total
    });
    
    // 重置当前页面
    currentPage.value = 0;
  } catch (e) {
    console.error('获取商品数据失败:', e);
  }
};

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(list.value.length / itemsPerPage);
});

// 是否显示左箭头
const showLeftArrow = computed(() => {
  return list.value.length > itemsPerPage && currentPage.value > 0;
});

// 是否显示右箭头
const showRightArrow = computed(() => {
  return list.value.length > itemsPerPage && currentPage.value < totalPages.value - 1;
});

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value - 1) {
    currentPage.value++;
    scrollToPage(currentPage.value);
  }
};

// 上一页
const upPage = () => {
  if (currentPage.value > 0) {
    currentPage.value--;
    scrollToPage(currentPage.value);
  }
};

// 滚动到指定页面
const scrollToPage = (pageIndex: number) => {
  if (recommendingListRef.value) {
    const scrollLeft = pageIndex * pageWidth;
    recommendingListRef.value.scrollTo({
      left: scrollLeft,
      behavior: 'smooth'
    });
  }
};

// 跳转详情
const toDetails = (dataItem: any) => {
  router.push({
    path: "/details",
    query: {
      id: dataItem.goodsId,
    },
  });
};
</script>

<template>
  <div class="recommending-box" v-if="pages">
    <div class="recommending-line">
      <img
        v-if="showLeftArrow"
        @click="upPage"
        class="more-left"
        src="~/assets/more-left-active.png"
        alt="上一页"
      />
      <RecommendingTitle
        :title="props.defaultType.name"
        :recommendingData="props.defaultType"
        subTitle=""
        :moreUrl="true"
      />
      <div class="recommending-list" ref="recommendingListRef">
        <RecommendingItem
          v-for="(item, index) of list"
          :key="item.id"
          :dataItem="item"
          :itemIndex="index"
          @refresh="toDetails"
          class="recommending-item"
        />
      </div>
      <img
        v-if="showRightArrow"
        @click="nextPage"
        class="more-right"
        src="~/assets/more-right-active.png"
        alt="下一页"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.recommending-box {
  width: 1200px;
  margin: 0 auto;
}

.recommending-line {
  position: relative;

  .more-left {
    position: absolute;
    top: 50%;
    left: -60px;
    width: 48px;
    height: 48px;
    cursor: pointer;
    margin-top: -24px;
    z-index: 10;
    transition: opacity 0.3s ease;

    &:hover {
      opacity: 0.8;
    }
  }

  .more-right {
    position: absolute;
    top: 50%;
    right: -60px;
    width: 48px;
    height: 48px;
    cursor: pointer;
    margin-top: -24px;
    z-index: 10;
    transition: opacity 0.3s ease;

    &:hover {
      opacity: 0.8;
    }
  }

  .recommending-list {
    width: 1200px;
    overflow: hidden; // 隐藏滚动条，只显示当前页的4个项目
    display: flex;
    flex-wrap: nowrap;
    scroll-behavior: smooth;

    .recommending-item {
      flex: 0 0 288px; // 固定宽度，精确计算确保4个项目完全填满1200px
      margin-right: 16px;

      &:nth-child(4n) {
        margin-right: 0; // 每4个项目的最后一个不要右边距
      }

      // 确保最后一个项目也没有右边距
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
